API Gateway এবং Client-Side Security মাইক্রোসার্ভিস আর্কিটেকচারে অত্যন্ত গুরুত্বপূর্ণ। API Gateway একটি মিডলওয়্যার হিসেবে কাজ করে, যা বিভিন্ন সার্ভিসের সাথে ক্লায়েন্টের যোগাযোগ পরিচালনা করে, এবং Client-Side Security আপনার ক্লায়েন্ট অ্যাপ্লিকেশনের নিরাপত্তা নিশ্চিত করে। নিচে উল্লিখিত বিষয়গুলোর বিশদ বর্ণনা দেওয়া হলো।
API Gateway হলো একটি সার্ভিস, যা ক্লায়েন্ট থেকে সমস্ত রিকোয়েস্ট গ্রহণ করে এবং সেগুলি সার্ভিসে পাঠানোর কাজ করে। এটি একাধিক মাইক্রোসার্ভিসের জন্য একটি একক এন্ট্রি পয়েন্ট হিসাবে কাজ করে।
Spring Boot অ্যাপ্লিকেশনে API Gateway হিসেবে Spring Cloud Gateway ব্যবহার করা হয়।
Maven pom.xml
-এ Spring Cloud Gateway এর ডিপেন্ডেন্সি যোগ করুন:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.cloud.gateway.config.GlobalFilter;
import org.springframework.cloud.gateway.filter.GlobalFilterChain;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.GatewayFilterFactory;
import org.springframework.web.server.ServerWebExchange;
@Configuration
public class GatewayConfig {
@Bean
public WebClient.Builder loadBalancedWebClientBuilder() {
return WebClient.builder();
}
@Bean
public GatewayFilter customFilter() {
return new GatewayFilter() {
@Override
public org.springframework.web.server.WebFilter.FilterChain filter(ServerWebExchange exchange, org.springframework.web.server.WebFilter.FilterChain chain) {
// Your custom logic here
return chain.filter(exchange);
}
};
}
}
Spring Cloud Gateway এর configuration application.yml
বা application.properties
ফাইলে করতে পারেন।
spring:
cloud:
gateway:
routes:
- id: myservice
uri: lb://my-service
predicates:
- Path=/my-service/**
filters:
- AddRequestHeader=X-Request-Foo, Bar
এই কনফিগারেশনে lb://
স্কিমা Load Balancer ব্যবহার করে এবং Path
অনুযায়ী রিকোয়েস্ট গাইড করবে।
Client-Side Security মূলত ক্লায়েন্ট অ্যাপ্লিকেশনের সুরক্ষা ব্যবস্থা যেমন Authentication, Authorization, Encryption, এবং Session Management নিয়ে কাজ করে।
Spring Boot API থেকে JWT টোকেন প্রাপ্ত করার জন্য নিম্নলিখিত কনফিগারেশন করতে হবে:
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.util.StringUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
public class JwtAuthenticationFilter extends OncePerRequestFilter {
private String jwtSecretKey = "secretKey"; // Your JWT Secret Key
@Override
protected void doFilterInternal(HttpServletRequest request, javax.servlet.http.HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
String jwtToken = getJwtFromRequest(request);
if (StringUtils.hasText(jwtToken) && validateToken(jwtToken)) {
Authentication authentication = getAuthentication(jwtToken);
SecurityContextHolder.getContext().setAuthentication(authentication);
}
filterChain.doFilter(request, response);
}
private String getJwtFromRequest(HttpServletRequest request) {
String bearerToken = request.getHeader("Authorization");
if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
return bearerToken.substring(7);
}
return null;
}
private boolean validateToken(String token) {
// Validate JWT Token here (use libraries like jjwt or io.jsonwebtoken)
return true; // Example: Assume token is valid
}
private Authentication getAuthentication(String token) {
// Create and return the Authentication object based on the token
return new UsernamePasswordAuthenticationToken("user", null, new ArrayList<>());
}
}
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/login", "/public/**").permitAll()
.anyRequest().authenticated()
.and()
.addFilter(new JwtAuthenticationFilter());
}
}
import org.springframework.http.HttpHeaders;
import org.springframework.web.client.RestTemplate;
public class AuthClient {
public static void main(String[] args) {
String token = "your-jwt-token-here";
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + token);
RestTemplate restTemplate = new RestTemplate();
String url = "http://localhost:8080/protected-endpoint";
String response = restTemplate.getForObject(url, String.class, headers);
System.out.println(response);
}
}
Spring Security এর মাধ্যমে CORS কনফিগারেশন করতে পারেন যাতে একটি সিকিউর ক্লায়েন্ট এবং সার্ভারের মধ্যে সঠিকভাবে রিকোয়েস্ট ট্রান্সফার হয়।
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://localhost:3000") // Allowed client-side origins
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowedHeaders("*")
.allowCredentials(true);
}
}
এই দুটি বিষয় মাইক্রোসার্ভিস আর্কিটেকচারে অপরিহার্য, কারণ এটি আপনার অ্যাপ্লিকেশনের সুরক্ষা এবং স্কেলেবিলিটি নিশ্চিত করে।
API Gateway হল একটি সার্ভিস যা একাধিক ব্যাকএন্ড সার্ভিসের জন্য একক পয়েন্ট হিসেবে কাজ করে। এটি বিভিন্ন মাইক্রোসার্ভিসে থাকা API গুলির রিকোয়েস্ট এবং রেসপন্সগুলিকে কেন্দ্রীয়ভাবে পরিচালনা করে। API Gateway এর মাধ্যমে আমরা সার্ভিস রিকোয়েস্ট গুলি সেন্ট্রালাইজড ও একত্রিতভাবে পরিচালনা, মনিটরিং এবং সিকিউরিটি নিশ্চিত করতে পারি।
API Gateway হল একটি আর্কিটেকচারাল প্যাটার্ন যা মাইক্রোসার্ভিস অ্যাপ্লিকেশনের জন্য খুবই উপকারী। এটি এক বা একাধিক ব্যাকএন্ড সার্ভিসে আগত রিকোয়েস্টগুলিকে রাউট, রিজেক্ট বা প্রসেস করতে সাহায্য করে। API Gateway মূলত Client এবং Microservices এর মধ্যে ব্রোকার হিসেবে কাজ করে।
API Gateway প্রথমে ক্লায়েন্ট (যেমন: ওয়েব ব্রাউজার, মোবাইল অ্যাপ্লিকেশন) থেকে একটি HTTP রিকোয়েস্ট গ্রহণ করে।
API Gateway রিকোয়েস্টের ওপর বিভিন্ন ধরনের কাজ করতে পারে:
API Gateway উপরের কাজগুলো করার পর, ব্যাকএন্ড মাইক্রোসার্ভিসগুলোর মধ্যে নির্দিষ্ট সার্ভিসে রিকোয়েস্ট রিডাইরেক্ট করে।
যখন ব্যাকএন্ড সার্ভিস থেকে রেসপন্স আসে, API Gateway রেসপন্সটি ক্লায়েন্টকে পাঠায়। এছাড়াও, API Gateway রেসপন্সের ওপর কিছু অতিরিক্ত কাজ করতে পারে (যেমন ডাটা ট্রান্সফরমেশন বা ক্যাশিং)।
API Gateway এর মাধ্যমে সার্ভিসগুলির মধ্যে ট্র্যাফিক মনিটরিং এবং লগিং করা যায়। এর মাধ্যমে সার্ভিসের স্বাস্থ্য পর্যবেক্ষণ, লেটেন্সি, এবং ব্যান্ডউইথ ব্যবহারের তথ্য পাওয়া যায়।
Spring Cloud Gateway হল Spring Framework এর একটি প্রকল্প যা API Gateway হিসেবে কাজ করতে পারে। এটি non-blocking, reactive ভিত্তিতে কাজ করে এবং API Gateway তৈরি করতে খুবই সুবিধাজনক।
Spring Cloud Gateway ব্যবহার করতে নিচের ডিপেনডেন্সি যুক্ত করুন।
Maven:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
Gradle:
implementation 'org.springframework.cloud:spring-cloud-starter-gateway'
application.yml
ফাইলে API Gateway কনফিগার করা যায়।
spring:
cloud:
gateway:
routes:
- id: myService
uri: lb://my-service-name
predicates:
- Path=/api/**
filters:
- AddRequestHeader=X-Request-Foo, Bar
Path
, Host
, Method
, ইত্যাদি।Spring Cloud Gateway ব্যবহার করে API গুলিকে সহজেই রাউট করতে পারেন।
@Configuration
public class GatewayConfig {
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
return builder.routes()
.route(r -> r.path("/get")
.uri("http://httpbin.org:80"))
.route(r -> r.host("*.circuitbreaker.com")
.filters(f -> f.circuitBreaker(c -> c.setName("mycmd")
.setFallbackUri("forward:/fallback")))
.uri("http://httpbin.org:80"))
.build();
}
}
API Gateway হলো একটি গুরুত্বপূর্ণ উপাদান, যা মাইক্রোসার্ভিস আর্কিটেকচারে একাধিক সার্ভিসের মধ্যে যোগাযোগ ও রিকোয়েস্ট প্রক্রিয়াকরণ সহজ করে। Spring Cloud Gateway একটি শক্তিশালী এবং কনফিগারেবল API Gateway, যা Spring Boot অ্যাপ্লিকেশনগুলির জন্য আদর্শ সমাধান।
প্রয়োজন হলে আরও বিস্তারিত বা উদাহরণ জানতে বলুন! 😊
Spring Cloud Gateway হল একটি API গেটওয়ে, যা ক্লায়েন্ট-সাইড সিকিউরিটি এবং রুটিং টাস্কের জন্য ব্যবহৃত হয়। এটি আপনাকে বিভিন্ন সার্ভিসের উপর লোড ব্যালেন্সিং, সিকিউরিটি এবং রেট লিমিটিং সমর্থন সহ একটি কাস্টম গেটওয়ে সেটআপ করতে দেয়।
এই গেটওয়ে সাধারণত সার্ভিস-মেশ বা মাইক্রোসার্ভিস আর্কিটেকচারে ব্যবহৃত হয়। Spring Cloud Gateway-এ সিকিউরিটি ইন্টিগ্রেশন বিভিন্ন পদ্ধতিতে করা যেতে পারে, যেমন JWT (JSON Web Tokens), OAuth2, বা Basic Authentication। এই গেটওয়ে সার্ভিসে গেটওয়ে লেভেলে সিকিউরিটি নিশ্চিত করার পাশাপাশি ক্লায়েন্ট সাইডে সিকিউরিটি হ্যান্ডল করার জন্য কিছু কনফিগারেশন করা যায়।
প্রথমে, আপনার Spring Boot অ্যাপ্লিকেশনটি Spring Cloud Gateway হিসেবে কনফিগার করতে হবে।
pom.xml
ফাইলে নিচের ডিপেন্ডেন্সি যোগ করুন:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-client</artifactId>
</dependency>
application.yml
বা application.properties
ফাইলে Spring Cloud Gateway কনফিগারেশন করুন, যাতে API রুটিং এবং সিকিউরিটি সিস্টেম ঠিকভাবে কাজ করে।
spring:
cloud:
gateway:
routes:
- id: user-service
uri: lb://user-service
predicates:
- Path=/users/**
filters:
- AddRequestHeader=X-Request-Foo, Bar
- AddResponseHeader=X-Response-Foo, Baz
# Example of security configuration
security:
oauth2:
client:
registration:
google:
client-id: YOUR-CLIENT-ID
client-secret: YOUR-CLIENT-SECRET
scope: profile, email
redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"
authorization-grant-type: authorization_code
client-name: Google
provider:
google:
authorization-uri: https://accounts.google.com/o/oauth2/auth
token-uri: https://oauth2.googleapis.com/token
user-info-uri: https://www.googleapis.com/oauth2/v3/userinfo
এই কনফিগারেশনটি Spring Cloud Gateway-এ OAuth2-এর মাধ্যমে ক্লায়েন্ট সাইড সিকিউরিটি চালু করে, এবং গুগল OAuth2 প্রোভাইডার ব্যবহার করে ইউজারের লগইন এবং অথোরাইজেশন সেটআপ করে।
ক্লায়েন্ট-সাইড সিকিউরিটির জন্য, OAuth2
সিকিউরিটি ব্যবহার করার মাধ্যমে Spring Cloud Gateway অ্যাপ্লিকেশন সুরক্ষিত করা যেতে পারে। নিচে OAuth2 সিকিউরিটি ইন্টিগ্রেশন এর উদাহরণ দেওয়া হলো:
Spring Cloud Gateway ক্লায়েন্ট হিসেবে OAuth2 এর সাহায্যে API কলগুলির সিকিউরিটি নিশ্চিত করতে, OAuth2 Client Configuration করতে হয়। spring-security-oauth2-client
ডিপেনডেন্সি যুক্ত করুন এবং application.yml
ফাইলে সঠিক কনফিগারেশন দিন।
spring:
security:
oauth2:
client:
registration:
google:
client-id: YOUR-CLIENT-ID
client-secret: YOUR-CLIENT-SECRET
scope: profile, email
authorization-grant-type: authorization_code
redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"
client-name: Google
provider:
google:
authorization-uri: https://accounts.google.com/o/oauth2/auth
token-uri: https://oauth2.googleapis.com/token
user-info-uri: https://www.googleapis.com/oauth2/v3/userinfo
OAuth2LoginAuthenticationFilter
ব্যবহার করে Spring Security এর সাহায্যে সিকিউরিটি কনফিগার করতে হবে। এই ফিল্টার ক্লায়েন্ট সাইডে সিকিউরিটি ভ্যালিডেশন করবে।
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableOAuth2Sso;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
@EnableOAuth2Sso
public class SecurityConfig {
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/login/**", "/error", "/oauth2/**").permitAll()
.anyRequest().authenticated()
.and()
.oauth2Login(); // Enable OAuth2 login
return http.build();
}
}
এটি OAuth2 সিকিউরিটি সিস্টেম তৈরি করবে যা গুগল বা অন্য OAuth2 প্রোভাইডার দ্বারা অ্যাক্সেস কন্ট্রোল নিশ্চিত করবে।
Spring Cloud Gateway এর সাথে JWT ব্যবহার করে সিকিউরিটি ইন্টিগ্রেশন করার জন্য, আপনাকে কিছু ফিল্টার এবং স্ট্র্যাটেজি কনফিগার করতে হবে।
একটি কাস্টম ফিল্টার তৈরি করুন যা JWT টোকেন যাচাই করবে এবং নিরাপদ API রিকোয়েস্ট অনুমোদন করবে।
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
@Component
public class JwtTokenFilter implements WebFilter {
private final JwtDecoder jwtDecoder;
public JwtTokenFilter(JwtDecoder jwtDecoder) {
this.jwtDecoder = jwtDecoder;
}
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
String token = exchange.getRequest().getHeaders().getFirst("Authorization");
if (token != null && token.startsWith("Bearer ")) {
String jwtToken = token.substring(7);
Jwt jwt = jwtDecoder.decode(jwtToken); // Validate and decode JWT token
// Further processing can be done here, e.g., setting user details in SecurityContext
}
return chain.filter(exchange);
}
}
এই ফিল্টারটি Spring Cloud Gateway এর রুট ফিল্টার হিসেবে যুক্ত করা যাবে। এইভাবে আপনি API গেটওয়ে লেভেলে সিকিউরিটি নিশ্চিত করতে পারবেন।
spring:
cloud:
gateway:
filters:
- name: JwtTokenFilter
application.yml-এ OAuth2 সেটআপ:
spring:
security:
oauth2:
client:
registration:
google:
client-id: YOUR-CLIENT-ID
client-secret: YOUR-CLIENT-SECRET
scope: profile, email
authorization-grant-type: authorization_code
redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"
client-name: Google
provider:
google:
authorization-uri: https://accounts.google.com/o/oauth2/auth
token-uri: https://oauth2.googleapis.com/token
user-info-uri: https://www.googleapis.com/oauth2/v3/userinfo
cloud:
gateway:
routes:
- id: user-service
uri: lb://user-service
predicates:
- Path=/users/**
SecurityConfig.java:
@Configuration
@EnableWebSecurity
@EnableOAuth2Sso
public class SecurityConfig {
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/login/**", "/error", "/oauth2/**").permitAll()
.anyRequest().authenticated()
.and()
.oauth2Login();
return http.build();
}
}
এইভাবে, Spring Cloud Gateway এর সাথে ক্লায়েন্ট-সাইড সিকিউরিটি ইন্টিগ্রেশন করতে পারেন, যা নিরাপদ এবং স্কেলেবল API গেটওয়ে প্রদান করবে।
স্প্রিং বুট ক্লায়েন্টে API Gateway এর মাধ্যমে Rate Limiting এবং Authentication কনফিগারেশন করার জন্য সাধারণত Spring Cloud Gateway এবং Spring Security ব্যবহার করা হয়। এটি মাইক্রোসার্ভিস আর্কিটেকচারে API গেটওয়ের মাধ্যমে রিকোয়েস্ট পরিচালনা এবং সুরক্ষা নিশ্চিত করতে সহায়তা করে।
Spring Cloud Gateway একটি API গেটওয়ে হিসেবে কাজ করে এবং এটি Rate Limiting এবং Authentication পরিচালনা করতে সহায়ক। নিচে এর কনফিগারেশন দেয়া হলো।
Maven:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
Gradle:
implementation 'org.springframework.cloud:spring-cloud-starter-gateway'
implementation 'org.springframework.boot:spring-boot-starter-security'
Spring Cloud Gateway এ Rate Limiting কনফিগার করতে Redis ব্যবহার করা হয়। এর মাধ্যমে নির্দিষ্ট সময়ের মধ্যে কতগুলো রিকোয়েস্ট অনুমোদিত হবে তা কনফিগার করা যায়।
application.yml
ফাইলে Rate Limiting কনফিগারেশন:spring:
cloud:
gateway:
routes:
- id: api_route
uri: http://example-service
predicates:
- Path=/api/**
filters:
- name: RequestRateLimiter
args:
redis-rate-limiter.replenishRate: 10
redis-rate-limiter.burstCapacity: 20
redis-rate-limiter.requestedTokens: 1
redis:
host: localhost
port: 6379
replenishRate
: প্রতি সেকেন্ডে কতগুলো টোকেন রিফিল হবে।burstCapacity
: একসাথে সর্বোচ্চ কতগুলো রিকোয়েস্ট অনুমোদিত।requestedTokens
: প্রতি রিকোয়েস্টের জন্য কতগুলো টোকেন প্রয়োজন।Spring Cloud Gateway এ Authentication সেটআপ করার জন্য Spring Security ব্যবহার করা হয়। সাধারণত JWT (JSON Web Token) এর মাধ্যমে Authentication এবং Authorization কনফিগার করা হয়।
SecurityConfig.java
এ Spring Security কনফিগারেশন:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/api/**").authenticated() // Only authenticated users can access /api/**
.anyRequest().permitAll()
.and()
.oauth2Login(); // Using OAuth2 login
}
}
JWT ব্যবহার করে API Gateway এর মাধ্যমে Authentication কনফিগার করার উদাহরণ:
Spring Security তে JWT Authentication ফিল্টার যোগ করতে হবে যা গেটওয়ের জন্য সমস্ত রিকোয়েস্টকে যাচাই করবে।
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
private static final String SECRET_KEY = "your_secret_key"; // Secret key for signing JWT
@Override
protected void doFilterInternal(HttpServletRequest request, javax.servlet.http.HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
String token = request.getHeader("Authorization");
if (token != null && token.startsWith("Bearer ")) {
token = token.substring(7); // Remove "Bearer " prefix
try {
String username = Jwts.parser()
.setSigningKey(SECRET_KEY)
.parseClaimsJws(token)
.getBody()
.getSubject();
if (username != null) {
// Authentication logic here (populate SecurityContext)
}
} catch (Exception e) {
response.setStatus(403); // Forbidden
}
}
filterChain.doFilter(request, response); // Continue the filter chain
}
}
JWT Authentication Filter যোগ করতে WebSecurityConfigurerAdapter ক্লাসে আপডেট করুন:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final JwtAuthenticationFilter jwtAuthenticationFilter;
public SecurityConfig(JwtAuthenticationFilter jwtAuthenticationFilter) {
this.jwtAuthenticationFilter = jwtAuthenticationFilter;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/api/**").authenticated() // Only authenticated users can access /api/**
.anyRequest().permitAll()
.and()
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class); // Add JWT filter
}
}
Spring Cloud Gateway এ API Rate Limiting এবং Authentication একত্রে কনফিগার করতে application.yml ফাইলে দুইটি ফিচারই কনফিগার করা যায়।
spring:
cloud:
gateway:
routes:
- id: api_route
uri: http://example-service
predicates:
- Path=/api/**
filters:
- name: RequestRateLimiter
args:
redis-rate-limiter.replenishRate: 10
redis-rate-limiter.burstCapacity: 20
redis-rate-limiter.requestedTokens: 1
- name: AddRequestHeader
args:
name: Authorization
value: "Bearer your_token_here"
redis:
host: localhost
port: 6379
@EnableWebSecurity
ব্যবহার করে Spring Security কনফিগারেশন সম্পন্ন করতে পারবেন।এই পদ্ধতিগুলো ব্যবহার করে আপনি Spring Cloud Gateway এর মাধ্যমে Rate Limiting এবং Authentication কনফিগার করতে পারবেন।
API Gateway হল একটি সার্ভিস যা বিভিন্ন মাইক্রোসার্ভিসে একক প্রবেশপথ হিসেবে কাজ করে এবং ক্লায়েন্টের জন্য একাধিক সার্ভিসে রিকোয়েস্ট পাঠানোর কাজে সহায়ক হয়। এটি সাধারণত রাউটিং, লোড ব্যালান্সিং, অথেনটিকেশন, রেট লিমিটিং, এবং অন্যান্য ফিচার পরিচালনা করতে ব্যবহৃত হয়।
Spring Boot অ্যাপ্লিকেশনের মধ্যে API Gateway Integration করার জন্য Spring Cloud Gateway একটি জনপ্রিয় টুল, যা API Gateway হিসেবে কাজ করে।
এখানে Spring Boot Client এর মধ্যে API Gateway Integration এর উদাহরণ দেখানো হলো।
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
Spring Cloud Gateway API Gateway হিসেবে কাজ করার জন্য application.yml
কনফিগারেশন ফাইল ব্যবহার করা হয়। এই কনফিগারেশনে বিভিন্ন রুট এবং ফিল্টার সেট করা যায়।
spring:
cloud:
gateway:
routes:
- id: api-service
uri: http://localhost:8081 # Target service URI
predicates:
- Path=/api/** # Matching API requests
filters:
- AddRequestHeader=X-Request-Foo, Bar # Request header filter
এখানে http://localhost:8081
সার্ভিসে যেকোনো /api/**
পাথে রিকোয়েস্ট রুট করা হচ্ছে এবং "X-Request-Foo: Bar" হেডার যুক্ত করা হচ্ছে।
ধরা যাক, আমাদের দুইটি মাইক্রোসার্ভিস রয়েছে:
এখন API Gateway এর মাধ্যমে রিকোয়েস্ট পাঠানোর জন্য Service A এবং Service B দুইটি স্প্রিং বুট অ্যাপ্লিকেশন তৈরি করা হবে।
Service A একটি সহজ Spring Boot অ্যাপ্লিকেশন যা /api/data
এ রেসপন্স দেয়।
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ServiceAController {
@GetMapping("/api/data")
public String getData() {
return "Data from Service A";
}
}
Service A এই রেসপন্সটি /api/data
পাথের জন্য প্রদান করবে।
Service B অন্য একটি Spring Boot অ্যাপ্লিকেশন যা Service A
এর রাউটের মাধ্যমে কল করবে।
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class ServiceBController {
private final RestTemplate restTemplate = new RestTemplate();
@GetMapping("/api/data-from-a")
public String getDataFromA() {
String url = "http://localhost:8080/api/data"; // API Gateway route
return restTemplate.getForObject(url, String.class);
}
}
Service B-এর /api/data-from-a
রাউটটি Service A থেকে ডেটা নিয়ে আসবে API Gateway এর মাধ্যমে।
এখন ক্লায়েন্ট অ্যাপ্লিকেশন তৈরি করা হবে যা API Gateway এর মাধ্যমে Service A এর /api/data
রাউটটিতে কল করবে।
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class ClientController {
private final RestTemplate restTemplate = new RestTemplate();
@GetMapping("/get-data")
public String getData() {
// API Gateway থেকে Service A এর ডেটা ফেচ করা
String apiGatewayUrl = "http://localhost:8080/api/data"; // API Gateway URL
return restTemplate.getForObject(apiGatewayUrl, String.class);
}
}
এখানে http://localhost:8080/api/data
URL ক্লায়েন্টের মাধ্যমে API Gateway থেকে কল হচ্ছে। API Gateway, সার্ভিস A তে রিকোয়েস্ট পাঠাবে এবং সেখান থেকে রেসপন্স ফিরে আসবে।
এখানে API Gateway এর routes
কনফিগারেশন করা হচ্ছে, যাতে নির্দিষ্ট পাথ /api/**
এ ক্লায়েন্ট রিকোয়েস্ট এসে একটি নির্দিষ্ট সার্ভিসে পৌঁছাতে পারে।
uri: http://localhost:8081
: Target সার্ভিসের URL যেখানে API Gateway রিকোয়েস্ট রাউট করবে।predicates
: এগুলো হল শর্ত যা যাচাই করে রিকোয়েস্টটি কোথায় রাউট হবে।filters
: অতিরিক্ত হেডার বা মডিফিকেশন যা রিকোয়েস্টে করা হয়।spring:
cloud:
gateway:
routes:
- id: service-a
uri: lb://SERVICE-A # Service Discovery via Eureka
predicates:
- Path=/api/** # Matching API requests
এখানে Service Discovery ব্যবহার করা হচ্ছে। যদি সার্ভিসগুলি Eureka বা অন্য কোনো সার্ভিস ডিসকভারি সিস্টেমে রেজিস্টার থাকে, তবে API Gateway সেই সার্ভিসগুলোর দিকে রিকোয়েস্ট পাঠাবে।
/api/data
পাথের মাধ্যমে ডেটা সরবরাহ করবে।/api/data-from-a
পাথের মাধ্যমে Service A থেকে ডেটা নেবে।/get-data
পাথের মাধ্যমে API Gateway এর মাধ্যমে Service A থেকে ডেটা ফেচ করবে।GET http://localhost:8082/get-data
এটি API Gateway এর মাধ্যমে Service A তে কল পাঠাবে এবং Service A থেকে ডেটা ফিরিয়ে আনবে।
Spring Boot Client এর মাধ্যমে API Gateway Integration ব্যবহার করে আপনি একাধিক মাইক্রোসার্ভিসের মধ্যে রিকোয়েস্ট রাউটিং, অথেনটিকেশন, ফিল্টারিং, এবং লোড ব্যালান্সিং পরিচালনা করতে পারেন। Spring Cloud Gateway এর মাধ্যমে এই ফিচারগুলো সহজেই ইমপ্লিমেন্ট করা সম্ভব।
Read more